<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\admin\model\Article as ArticleModel;
use think\Request;

/**
 * 文章管理接口
 */
class Article extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取文章列表
     */
    public function index()
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $city_id = $this->request->param('city_id', '');
        $school_id = $this->request->param('school_id', '');
        $keyword = $this->request->param('keyword', '');

        $articleModel = new ArticleModel();
        $query = $articleModel->where('status', 1);

        // 城市筛选 - 注意字段名是cityid而不是city_id
        if ($city_id) {
            $query->where('city_id', $city_id);
        }

        // 学校筛选 - 注意字段名是schoolid而不是school_id
        if ($school_id) {
            $query->where('school_id', $school_id);
        }

        // 关键词搜索
        if ($keyword) {
            $query->where('title', 'like', '%' . $keyword . '%');
        }

        $total = $query->count();
        $list = $query->order('id', 'desc')
            ->page($page, $limit)
            ->select();

        // 格式化数据，确保字段名一致性
        $rows = [];
        foreach ($list as $item) {
            $rows[] = [
                'id' => $item['id'],
                'title' => $item['title'],
                'city_id' => $item['city_id'],
                'school_id' => $item['school_id'],
                'create_time' => $item['create_time'],
                'status' => $item['status'],
                'image' => $item['cover'] // 使用cover字段作为图片
            ];
        }

        // bootstrap-table需要的数据格式
        $result = [
            'total' => $total,
            'rows' => $rows
        ];

        return json($result);
    }
}